package com.bytecodezz.app.toolset.idcard

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModelProvider
import com.bytecodezz.app.framework.base.model.BaseViewModel
import com.bytecodezz.app.toolset.base.BaseUIFragment
import com.bytecodezz.app.toolset.databinding.FragmentIdCardBinding
import com.bytecodezz.app.toolset.idcard.model.IDcardViewModel
import com.bytecodezz.app.toolset.launcher.model.LauncherViewModel
import com.bytecodezz.idcard.IDCardTools


/**
 * @author: bytecodezz
 * @version: 1.0
 * @time: 2021/7/7 13:33
 * @package: com.bytecodezz.app.toolset.idcard
 *
 * @description:
 *
 */
class IDcardFragment : BaseUIFragment<FragmentIdCardBinding, IDcardViewModel>() {
    private val WRITE_PERMISSION = 0x01
    private var ResultImage: Bitmap? = null
    private var fullImage: Bitmap? = null

    companion object {
        const val TAG = "IDcardFragment"
    }

    override fun onCreateViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentIdCardBinding.inflate(inflater, container, false)

    override fun onActivityViewModelProvider(): BaseViewModel? {
        return activity?.let {
            ViewModelProvider(it).get(LauncherViewModel::class.java)
        }
    }

    override fun onActionStart(contentView: View) {
        binding.closePagerButton.setOnClickListener {
            //关闭当前页面
            getActivityViewModel<LauncherViewModel>()?.closeFragmentPager(TAG)
        }
        binding.getVersionButton.setOnClickListener {
            IDCardTools().versionNative()
        }
        binding.searchButton.setOnClickListener {
            requestWritePermission()
        }
        binding.searchIdButton.setOnClickListener {
            searchId()
        }
        binding.recognitionTxtButton.setOnClickListener {
            IDCardTools().getTxtByBitmap(requireActivity(), ResultImage!!) {
                binding.tesstext.text = it
            }
        }
    }

    fun searchId() {
        ResultImage = null
        val bitmapResult: Bitmap =
            IDCardTools().getIDNumberBitmap(fullImage!!, Bitmap.Config.ARGB_8888)
        fullImage!!.recycle()
        ResultImage = bitmapResult
        //tesseract-ocr
        binding.idcard.setImageBitmap(bitmapResult)
    }

    fun search() {
        val intent: Intent
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            intent = Intent()
            intent.action = Intent.ACTION_GET_CONTENT
        } else {
            intent = Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            )
        }
        intent.type = "image/*"
        //使用选取器并自定义标题
        startActivityForResult(Intent.createChooser(intent, "选择待识别图片"), 100)
    }

    private fun getResult(uri: Uri?) {
//        safeRecycled();
        var imagePath: String? = null
        if (null != uri) {
            //在我们的魅族测试手机上发现有一个相册管家 从这里选取图片会得到类似
            //file:///storage/emulated/0/tencent/MicroMsg/WeiXin/mmexport1474966179606.jpg的uri
            if ("file" == uri.scheme) {
                imagePath = uri.path
            } else if ("content" == uri.scheme) {
                val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                val c: Cursor? = requireActivity().getContentResolver()
                    .query(uri, filePathColumns, null, null, null)
                if (null != c) {
                    if (c.moveToFirst()) {
                        val columnIndex = c.getColumnIndex(filePathColumns[0])
                        imagePath = c.getString(columnIndex)
                    }
                    c.close()
                }
            }
        }
        if (!TextUtils.isEmpty(imagePath)) {
            if (fullImage != null) {
                fullImage?.recycle()
            }
            fullImage = toBitmap(imagePath)
//            tesstext.setText(null)
            binding.idcard.setImageBitmap(fullImage)
        }
    }

    fun toBitmap(pathName: String?): Bitmap? {
        if (TextUtils.isEmpty(pathName)) return null
        val o = BitmapFactory.Options()
        o.inJustDecodeBounds = true
        BitmapFactory.decodeFile(pathName, o)
        var width_tmp = o.outWidth
        var height_tmp = o.outHeight
        var scale = 1
        while (true) {
            if (width_tmp <= 640 && height_tmp <= 480) {
                break
            }
            width_tmp /= 2
            height_tmp /= 2
            scale *= 2
        }
        val opts = BitmapFactory.Options()
        opts.inSampleSize = scale
        opts.outHeight = height_tmp
        opts.outWidth = width_tmp
        return BitmapFactory.decodeFile(pathName, opts)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && null != data) {
            getResult(data.data)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == WRITE_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            }
        }
    }


    private fun requestWritePermission() {
        if (requireActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                WRITE_PERMISSION
            )
        } else {
            search()
        }
    }
}